package com.SouthernWall_404.Age_Capitalism.common.World.Blocks;

import com.SouthernWall_404.Age_Capitalism.AgeCapitalism;
import com.SouthernWall_404.Age_Capitalism.common.Init.ModBlockEntities;
import com.SouthernWall_404.Age_Capitalism.common.Init.ModItems;
import com.SouthernWall_404.Age_Capitalism.common.World.Entity.StoreBlockEntity;
import com.SouthernWall_404.Age_Capitalism.common.World.Items.StoreKeyItem;
import com.SouthernWall_404.Age_Capitalism.common.World.Items.StoreTagItem;
import net.minecraft.core.BlockPos;
import net.minecraft.core.Direction;
import net.minecraft.nbt.CompoundTag;
import net.minecraft.server.level.ServerPlayer;
import net.minecraft.world.*;
import net.minecraft.world.entity.LivingEntity;
import net.minecraft.world.entity.player.Inventory;
import net.minecraft.world.entity.player.Player;
import net.minecraft.world.item.Item;
import net.minecraft.world.item.ItemStack;
import net.minecraft.world.item.context.BlockPlaceContext;
import net.minecraft.world.level.BlockGetter;
import net.minecraft.world.level.block.*;
import net.minecraft.world.level.block.entity.BlockEntity;
import net.minecraft.world.level.block.entity.BlockEntityType;
import net.minecraft.world.level.block.state.BlockState;
import net.minecraft.world.level.block.state.StateDefinition;
import net.minecraft.world.level.block.state.properties.BlockStateProperties;
import net.minecraft.world.level.block.state.properties.ChestType;
import net.minecraft.world.level.block.state.properties.EnumProperty;
import net.minecraft.world.phys.BlockHitResult;
import net.minecraft.world.phys.shapes.CollisionContext;
import net.minecraft.world.phys.shapes.Shapes;
import net.minecraft.world.phys.shapes.VoxelShape;
import net.minecraftforge.network.NetworkHooks;
import net.minecraft.world.level.Level;

public class StoreBlock extends BarrelBlock implements EntityBlock {

    public static final EnumProperty<ChestType> TYPE = BlockStateProperties.CHEST_TYPE;
    private VoxelShape shape=Shapes.create(0,0,0,1,1.5,1);
    public StoreBlock(Properties p_49046_) {
        super(p_49046_);
        this.registerDefaultState(this.stateDefinition.any()
                .setValue(FACING, Direction.NORTH).setValue(TYPE, ChestType.SINGLE));

    }
    protected void createBlockStateDefinition(StateDefinition.Builder<Block, BlockState> builder) {
        builder.add(FACING,OPEN,TYPE);
    }

    // 5. 处理放置时的方向
    @Override
    public BlockState getStateForPlacement(BlockPlaceContext context) {
        Direction horizontalDirection = context.getHorizontalDirection().getOpposite();
        return this.defaultBlockState().setValue(FACING, horizontalDirection);
    }
    @Override
    public BlockEntity newBlockEntity(BlockPos pos, BlockState state) {


        BlockEntity blockEntity=new StoreBlockEntity(pos, state){
            @Override
            public BlockEntityType<?> getType() {
                return ModBlockEntities.STORE_BLOCK_ENTITY.get();
            }
        };

        return blockEntity;
    }
    @Override
    public VoxelShape getShape(BlockState state, BlockGetter world, BlockPos pos, CollisionContext context) {
        return shape;

    }

    // 可选：重写遮挡形状（用于光照等）
    @Override
    public VoxelShape getOcclusionShape(BlockState state, BlockGetter world, BlockPos pos) {
        return shape;
    }

    // 可选：重写交互形状（玩家可点击的区域）
    @Override
    public VoxelShape getInteractionShape(BlockState state, BlockGetter world, BlockPos pos) {
        return shape;
    }


    @Override
    public InteractionResult use(BlockState blockState, Level level, BlockPos blockPos, Player player, InteractionHand interactionHand, BlockHitResult p_51536_) {
//
            ItemStack itemInHand = player.getItemInHand(InteractionHand.MAIN_HAND);
            Item item = itemInHand.getItem();
        if(player.isCreative()&&player.isShiftKeyDown()&&itemInHand.isEmpty())
        {
            ItemStack hand=player.getItemInHand(InteractionHand.MAIN_HAND);

            BlockEntity blockEntity=level.getBlockEntity(blockPos);
            CompoundTag keyPack=new CompoundTag();
            CompoundTag modPack=new CompoundTag();


            if(blockEntity instanceof  StoreBlockEntity storeBlockEntity)
            {
                keyPack.putString("uuid",storeBlockEntity.uuid);
                keyPack.putInt("x",blockPos.getX());
                keyPack.putInt("y",blockPos.getY());
                keyPack.putInt("z",blockPos.getZ());
                keyPack.putString("block",getName().getString());
                modPack.put("keyPack",keyPack);
            }




            return InteractionResult.SUCCESS;
        }
            if (!(item instanceof StoreKeyItem)&&!(item instanceof StoreTagItem)) {
                BlockEntity blockEntity = level.getBlockEntity(blockPos);


                if (blockEntity instanceof StoreBlockEntity storeBlockEntity && player instanceof ServerPlayer serverPlayer) {
                    storeBlockEntity.startTrading(serverPlayer);

                    return InteractionResult.sidedSuccess(storeBlockEntity.getLevel().isClientSide);
                }
//            player.sendSystemMessage(Component.translatable("1"));

            }
            if(!(item instanceof StoreTagItem))
            {
                BlockEntity blockEntity = level.getBlockEntity(blockPos);
                if (blockEntity instanceof StoreBlockEntity storeBlockEntity && player instanceof ServerPlayer serverPlayer) {

                    NetworkHooks.openScreen((ServerPlayer) player,(MenuProvider) storeBlockEntity, blockPos);
                    return InteractionResult.sidedSuccess(storeBlockEntity.getLevel().isClientSide);
                }
            }
            else if(item instanceof StoreTagItem)
            {
                BlockEntity blockEntity=level.getBlockEntity(blockPos);
//        player.sendSystemMessage(Component.literal(""+player.level()));
                if(blockEntity instanceof StoreBlockEntity storeBlockEntity)
                {
                    storeBlockEntity.startSettingTrading(player);
                    return InteractionResult.sidedSuccess(storeBlockEntity.getLevel().isClientSide);
                }
            }
            return InteractionResult.SUCCESS;

    }



    @Override
    public void setPlacedBy(Level level, BlockPos blockPos, BlockState blockState, LivingEntity livingEntity, ItemStack itemStack) {
        super.setPlacedBy(level, blockPos, blockState, livingEntity, itemStack);

        if(livingEntity instanceof Player player)
        {
            ItemStack hand=player.getItemInHand(InteractionHand.MAIN_HAND);
            ItemStack toGive=new ItemStack(ModItems.STORE_KEY.get(),1);

            BlockEntity blockEntity=level.getBlockEntity(blockPos);
            CompoundTag modPack=new CompoundTag();
            if(blockEntity instanceof  StoreBlockEntity storeBlockEntity)
            {
                modPack.put("keyPack",storeBlockEntity.getKey());
            }

            CompoundTag nbt=toGive.getOrCreateTag();
            nbt.put(AgeCapitalism.MODID,modPack);

            toGive.setTag(nbt);
            toGive.save(nbt);



            if(hand.isEmpty())
            {
                player.setItemInHand(InteractionHand.MAIN_HAND,toGive);
            }
            else if(!this.placeInInventory(player,toGive))
            {
                player.drop(toGive,true);
            }
        }
    }

    private boolean placeInInventory(Player player,ItemStack itemStack)
    {
        //需要注意，此函数有缺陷！不能用于常规放置！
        Inventory inventory=player.getInventory();

        for(int i=0;i<inventory.getContainerSize()-5;i++)
        {
            ItemStack currentItem=inventory.getItem(i);
            if(currentItem.isEmpty())
            {
                inventory.setItem(i,itemStack);
                return true;
            }

        }

        return false;
    }
}
